import datetime
from base import log, mysqlConnect


def insert(fromdate, todate, member_id, duration):
    logging = log.init(1)
    try:
        db, cursor = mysqlConnect.connect("sit", "kaikela_stat")
    except Exception as e:
        logging.error(e)
        print(e)
    sheet_name = "s_learn_time_statistics"
    logging.info("=================================================")
    fromtimedatetime = datetime.datetime.strptime(fromdate, "%Y-%m-%d")
    totimedatetime = datetime.datetime.strptime(todate, "%Y-%m-%d")
    delta = totimedatetime - fromtimedatetime
    days = delta.days + 1
    for i in range(0, days):
        learn_time = fromtimedatetime + datetime.timedelta(days=i)
        create_date = "create_date"
        learn_duration = duration
        lastvalues = [str(learn_time), member_id, str(learn_duration), str(create_date)]
        values = []
        for value in lastvalues:
            if value is create_date:
                newvalue = "NOW()"
            else:
                newvalue = "\'" + value + "\'"
            values.append(newvalue)
        sql = ""
        sql = sql + "INSERT INTO "
        sql = sql + sheet_name
        sql = sql + " (`learn_date`, `member_id`, `learn_duration`, `create_time`)"
        sql = sql + " VALUES ("
        sql = sql + ",".join(values)
        sql = sql + ")"
        logging.info("==========================开始执行SQL==========================")
        try:
            logging.info(sql)
            cursor.execute(sql)
            db.commit()
        except Exception as e:
            logging.info("==========================SQL执行失败==========================")
            logging.error(e)
